<template>
    <header class="header">
      <div class="logo">
        HC-TRPG
      </div>
      <div class="menu">
        <a-menu v-model:selectedKeys="current" mode="horizontal" @click="handleMenuClick" :items="items" theme="dark"/>
      </div>
      <div class="login">
          <a-button v-if="!authorizationed" type="text" size="large" style="color: white;" @click="showLoginModal">登录</a-button>
          <div v-else style="width: 100px; margin-right: 50px;">
            <a-avatar size="large" :src= "avatar" @click="showUserInfoModal"/>
          </div>
          <teleport to="body">
            <log-in :visible="loginModalVisible" @loginSuccess="handleLoginSuccess" @loginCancel="handleLoginCancel"/>
          </teleport>
          <teleport to="body">
            <user-info :visible="userInfoVisible" ref="userInfoRef" @updateCancel="handleUpdateCancel" @uploadSuccess="handleUploadSuccess" @updateSuccess="handleUpdateSuccess"/>
          </teleport>
      </div>
    </header>
  </template>

  <script lang="ts">
    export default {
      name: 'Header',
    };
  </script>
  
  <script lang="ts" setup>
    import LogIn from './logIn.vue';
    import UserInfo from './userInfo.vue'
    import { MenuProps } from 'ant-design-vue';
    import { ref, onMounted } from 'vue';
    import { getUserDetail } from '@/api/user_api';
    import router from '@/router/index';
    import { message } from 'ant-design-vue';

    const value = ref<string>('');
    const current = ref<string[]>(['main']);
    const items = ref<MenuProps['items']>([
      {
        key: 'main',
        label: '首页',
        title: '首页',
      },
      {
        key: 'character',
        label: '角色',
        title: '角色',
      },
      {
        key: 'script',
        label: '剧本',
        title: '剧本',
      },
      {
        key: 'room',
        label: '房间',
        title: '房间',
      },
      {
        key: 'forum',
        label: '论坛',
        title: '论坛',
      }
    ]);
    const loginModalVisible = ref<Boolean>(false)
    const avatar = ref<any>()
    const userInfoVisible = ref<Boolean>(false)
    const user = ref<any>()
    const userInfoRef = ref<any>()
    const authorizationed = ref(false)
    const refreshKey = ref<number>(0)

    onMounted(async () => {
      // 从LocalStorage中获取值
      const storedValue = localStorage.getItem('authorization');
      if (storedValue) {
        console.log(storedValue)
        // 去后端获取用户信息， 检查登录是否失效
        await getUserDetail()
        .then(resp => {
          user.value = resp.data
          authorizationed.value = true
          localStorage.setItem('uid', resp.data.uid)
          localStorage.setItem('avatar', resp.data.avatar)
          localStorage.setItem('username', resp.data.username)
          avatar.value = resp.data.avatar
        })
        .catch(resp => {
          authorizationed.value = false
        })
      }
      console.log(authorizationed.value == true)
    })

    // methods 
    const onSearch = (s: string) => { // 搜索
    };
    const showLoginModal = () => {
      loginModalVisible.value = true;
    };
    const handleLoginSuccess = (userInfo:any) => { // 处理登陆成功
      // 在这里处理登陆成功后的信息
      loginModalVisible.value = false; // 登陆成功后隐藏登陆窗口
      user.value = userInfo
      localStorage.setItem("uid", userInfo.uid);
      localStorage.setItem("username", userInfo.username)
      localStorage.setItem("avatar", userInfo.avatar)
      avatar.value = userInfo.avatar
      authorizationed.value = true
    };
    const handleLoginCancel = () => {
      loginModalVisible.value = false; // 隐藏登陆窗口
    }
    const showUserInfoModal = () => {
      userInfoVisible.value = true;
      userInfoRef.value.initUser(user.value)
    }
    const handleUpdateCancel = () => {
      userInfoVisible.value = false;
    }
    const handleUploadSuccess = (data:string) => {
      console.log(data)
      user.value.avatar = data
      avatar.value = data
      localStorage.setItem("avatar", data)
    }
    const handleUpdateSuccess = (data:any) => {
      console.log(data)
      userInfoVisible.value = false;
      user.value.phone = data.phone;
      user.value.username = data.username;
    }
    const handleMenuClick: MenuProps['onClick'] = async menuInfo => {
      if (menuInfo.key === 'character') {
        skip2Charactor()
      } else if (menuInfo.key === 'script') {
        skip2Scripts()
      } else if (menuInfo.key === 'room') {
        skip2Rooms()
      } else if (menuInfo.key === 'forum') {
        skip2Forum()
      } else {
        skip2Main();
      }
      refreshKey.value += 1
    };
    const skip2Charactor = () => {
        if (localStorage.getItem('authorization') === null) {
            message.error("请先登录！")
        } else {
            router.push( {name: 'character'} )
        }
    }
    const skip2Scripts = () => {
        if (localStorage.getItem('authorization') === null) {
            message.error("请先登录！")
        } else {
            router.push( {name: 'scripts'} )
        }
    }
    const skip2Rooms = () => {
        if (localStorage.getItem('authorization') === null) {
            message.error("请先登录！")
        } else {
            router.push( {name: 'rooms'} )
        }
    }
    const skip2Forum = () => {
      if (localStorage.getItem('authorization') === null) {
          message.error("请先登录！")
      } else {
          router.push( {name: 'forum'} )
      }
    }
    const skip2Main = () => {
      router.push( {name: 'main'} )
    }
  </script>
  
  <style scoped>
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    top: 0px;
    margin: 0px;
    padding: 10px;
    color: #000;
    background-color: #000;
  }
  .logo {
    margin-left: 100px;
    color: #fff;
    font-size: xx-large;
    font-weight: bolder;
    display: flex;
    align-items: center;
  }
  .menu {
    margin-left: 200px;
    color: #fff;
    font-size: xx-large;
    font-weight: bolder;
    display: flex;
    align-items: center;
  }
  .login {
    display: flex;
    align-items: center;
    width: 50px;
    size: 50px;
    color: #fff;
    margin-left: 10px;
    margin-right: 50px;
    width: 200px;
  }
  </style>